import {Button, DatePicker, Dropdown,Table, Tag, Radio, Divider, 
  Space, Drawer, Form, Input, Select, TreeSelect, message
} from 'antd';
import React, { useState, useEffect } from 'react';
import { getUserDataApi, delUserInfoApi, getDeptDataApi ,addUserApi} from '../../apis/user';
import { getRoleDataApi } from '../../apis/role'
import Search from './user/components/Search';
import AddUserDrawer from './user/components/AddUserDrawer'
import { SettingOutlined, EyeOutlined } from '@ant-design/icons';
import Modal from 'antd/lib/modal/Modal';
const { RangePicker } = DatePicker;

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
const validateMessages = {
  required: '${label} is required!',
  types: {
    email: '${label} is not a valid email!',
    number: '${label} is not a valid number!',
  },
  number: {
    range: '${label} must be between ${min} and ${max}',
  },
};


export default function User() {
  const [componentSize, setComponentSize] = useState('default');
  //存储用户数据
  const [userData, setUserData] = useState([]);
  //存储部门数据
  const [deptData, setDeptData] = useState([]);
  //存储角色数据
  const [roletData, setRoletData] = useState([]);
  const [value, setValue] = useState(1);
  //loading状态
  const [loading, setLoading] = useState(false);
  //用户总条数total
  const [total, setTotal] = useState();
  //复选框
  const [selectionType, setSelectionType] = useState('checkbox');
  //抽屉
  const [open, setOpen] = useState(false);
  const [size, setSize] = useState();
  //当前选中用户
  const curUserInfo = JSON.parse(localStorage.user);
  //存储选中数据
  const [checkedArr,setCheckedArr] = useState([]);

  const [placement, setPlacement] = useState('right');
  useEffect(() => {
    getUserData();
    getDeptData();
    getRoleData();
  }, []);
  //获取部门数据
  async function getDeptData() {
    const deptDate = await getDeptDataApi();
    setDeptData(deptDate.rows.children);
  }
  //获取角色数据
  async function getRoleData() {
    const roletDate = await getRoleDataApi();
    setRoletData(roletDate.rows);
    console.log("roletDate", roletDate);
  }
  async function getUserData(parms) {
    try {
      setLoading(true);
      const res = await getUserDataApi(parms);
      const datas = formatMenus(res.rows);
      setUserData(datas);
      setTotal(res.total);
      setLoading(false);
    } catch (error) {
      console.log("error", error);
      setLoading(false);
    }
  }
  //过滤数据
  function formatMenus(data) {
    return handleMenus(data)
    function handleMenus(data) {
      return data.map((item, index) => {
        const o = {
          ...item,
          tags: [item.status],
          ssexs: [item.ssex],
          key: item.userId,
        }
        return o;
      })
    }
  }
  //关闭抽屉
  const onClose = () => {
    setOpen(false);
  };
  //更多操作下拉选项数据
  const items = [
    {
      key: '1',
      label: "密码重置"
    },
    {
      key: '2',
      label: "导出Excel"
    },
  ];
  //表格
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      onFilter: (value, record) => record.name.indexOf(value) === 0,
      sorter: (a, b) => a.name.length - b.name.length,
      sortDirections: ['descend'],
    },
    {
      title: '性别',
      dataIndex: "ssex",
      defaultSortOrder: 'descend',
      render: (_, { ssexs }) => (
        <>
          {ssexs.map((ssex) => {
            if (ssex === '0') {
              ssex = "男"
            } else if (ssex === '1') {
              ssex = "女"
            }else if(ssex === '2'){
              ssex = "保密"
            }
            return (
                ssex
            );
          })}
        </>
      ),
      sorter: (a, b) => a.age - b.age,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      onFilter: (value, record) => record.address.indexOf(value) === 0,
    },
    {
      title: '部门',
      dataIndex: 'deptName',

    },
    {
      title: '电话',
      dataIndex: 'mobile',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = '';
            if (tag === '1') {
              tag = "有效"
              color = 'cyan';
            } else if (tag === '0') {
              tag = "锁定"
              color = 'red';
            }
            return (
              <Tag color={color} key={tag}>
                {tag}
              </Tag>
            );
          })}
        </>
      ),

    },
    {
      title: '创建时间',
      dataIndex: 'createTime',

    },
    {
      title: '操作',
      render: () => (<>
        <Space>
          <SettingOutlined
            style={{ color: "#1890FF" }} onClick={showDefaultDrawer} />
          <EyeOutlined style={{ color: "#52c41a" }} />
        </Space>
        {/* <AddUserDrawer /> */}

      </>)
    },
  ];
  //获取页数
  function onChange(pageNum, pageSize) {
    console.log("pageNum, pageSize", pageNum, pageSize);
    getUserData({ pageNum, pageSize })
  }
  const showDefaultDrawer = (curUserInfo) => {
    setSize('default');
    console.log("curUserInfo",curUserInfo);
    setOpen(true);
  };
  const onFinish = async (values) => {
    console.log("values", values);
    //新增用户
    const params = {
      deptId: values.user.deptId,
      email: values.user.email,
      mobile: values.user.mobile,
      password: values.user.password,
      roleId: values.user.roleId,
      // roleId:values.user.roleId.toString(),
      ssex: values.user.ssex,
      status: values.user.status,
      username: values.user.username,
    }
    const addUser = await addUserApi(params);
    //成功重新刷新页面  关闭抽屉
    message.success("新增成功");
    setOpen(false);

    console.log("addUser", addUser);
    // console.log("values",values);
  };
  //获取选中当前行
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setCheckedArr(selectedRows);
      // //调用删除
      // delUser(selectedRows);
    },
    getCheckboxProps: (record) => ({
      disabled: record.name === 'Disabled User',
      // Column configuration not to be checked
      name: record.name,
    }),
  };
  //删除
  async function delUser() {
    if(checkedArr.length){
      //选中
      console.log("选中");
      console.log("checkedArr",checkedArr);
      const ids = checkedArr.map(item=>item.userId).join(",");
      //获取所有用户名，用于提示
      const names = checkedArr.map(item=>item.username).join(",");
      const del = await delUserInfoApi(ids);
      message.success("删除成功");
      getUserData();
      console.log("dellll",del);
      console.log("ids",ids,names);
    }else{
      //未选中
      console.log("未选中");
      message.info("请选择要删除的用户")
    }
    // console.log("删除");
    // console.log("curUserInfo", curUserInfo);
    // //发送删除接口
    // const delRes = await delUserInfoApi(curUserInfo[0]);
    // console.log("delRes", delRes);

  }
  return (
    <div className='h100'>
      <Search />
      <div style={{ marginTop: "10px" }}>
        {/* <AddUserDrawer/> */}
        <Button style={{ marginLeft: "10px" }} onClick={showDefaultDrawer}>新增</Button>
        <Button onClick={delUser} style={{ marginLeft: "10px" }}>删除</Button>
        <Dropdown
          menu={{
            items,
          }}
          placement="bottom"
          arrow="true"
        >
          <Button style={{ marginLeft: "10px" }}>更多操作</Button>
        </Dropdown>

      </div>
      <div>
        <Radio.Group
          onChange={({ target: { value } }) => {
            setSelectionType(value);
            console.log("checkBoxValue", value);
          }}
          value={selectionType}
        >
        </Radio.Group>
        <Divider />
        <Table style={{ marginTop: "16px" }}
          loading={loading}
          columns={columns}
          dataSource={userData}
          // onChange={onChange}
          pagination={{
            total,
            onChange
          }}

          rowSelection={{
            type: selectionType,
            ...rowSelection,
            // onselect
          }}

        />
        {/* <AddUserDrawer /> */}

      </div>
      <Drawer
        title="新增用户"
        placement={placement}
        width={500}
        onClose={onClose}
        open={open}
        extra={
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button type="primary" onClick={onClose}>
              确定
            </Button>
          </Space>
        }
      >
        <Form {...layout} name="nest-messages" onFinish={onFinish} 
        validateMessages={validateMessages}
        >
          <Form.Item
            name={['user', 'username']}
            label="用户名"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name={['user', 'password']}
            rules={[
              {
                required: true,
                message: '请输入你的密码',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name={['user', 'email']}
            label="邮箱"
          >
            <Input />
          </Form.Item>
          <Form.Item
            name={['user', 'mobile']}
            label="手机"
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="角色"
            name={['user', 'roleId']}
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Select>
              {
                roletData.map(item => {
                  return <Select.Option key={item.roleId} value={item.roleId}>{item.roleName}</Select.Option>
                })
              }

            </Select>
          </Form.Item>
          <Form.Item label="部门" name={['user', 'deptId']}>
            <TreeSelect
              treeData={deptData}
            />
          </Form.Item>
          <Form.Item label="状态" name={['user', 'status']}
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Radio.Group onChange={onChange} value={value}>
              <Radio value={"0"}>锁定</Radio>
              <Radio value={"1"}>有效</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="性别" name={['user', 'ssex']}
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Radio.Group onChange={onChange} value={value}>
              <Radio value={"0"}>男</Radio>
              <Radio value={"1"}>女</Radio>
              <Radio value={"2"}>保密</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            wrapperCol={{
              ...layout.wrapperCol,
              offset: 8,
            }}
          >
            <Space>
              <Button onClick={onClose}>取消</Button>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Space>

          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}
